import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'
Vue.use(Vuex)

const store = () => new Vuex.Store({
  modules: {
    // ...f2eSDKModules
  },
  state: {
    token: null,
    user: {},
    role: {},
    permissions: {},
    environments: []
  },
  mutations: {
    SET_TOKEN(state, data) {
      if (typeof data === 'string') {
        state.token = data
      } else {
        state.token = data.token
        state.role = data.admin
      }
    },
    CLEAR_TOKEN(state) {
      state.token = null
    },
    SET_USER(state, data) {
      state.user = data.data
    },
    SET_PERMISSIONS(state, data) {
      state.permissions = data
    },
    SET_ENVIRONMENTS(state, data) {
      state.environments = data
    }
  },
  actions: {
    // nuxt服务端初始化方法，优先级比路由中间件还高。ssr前端向node端发送的请求都会经过该方法
    async nuxtServerInit({ dispatch, commit, state }, { req, res }) {
      // 刷新页面 cookie丢失重新获取
      let token = ''
      if (req.headers.cookie) {
        let cookie = req.headers.cookie
        let cookieObj = {}
        let cookieArr = []
        let key = ''
        let value = ''
        cookie = cookie.split(';')
        for (let i = 0; i < cookie.length; i++) {
          cookieArr = cookie[i].trim().split('=')
          key = cookieArr[0]
          value = cookieArr[1]
          cookieObj[key] = value
        }
        // 防止F5刷新，store中 session丢失
        if (cookieObj['token'] && req.url !== '/login') {
          commit('SET_TOKEN', cookieObj['token'])
          token = cookieObj['token']
        }
      }
      // 重新获取permissions
      axios.defaults.headers.token = token
      await axios.get('/api/auth/permissions').then((res) => {
        if (res && res.data) {
          commit('SET_PERMISSIONS', res.data)
        } else {
          commit('CLEAR_TOKEN')
        }
      }).catch(() => {
        commit('CLEAR_TOKEN')
      })
    }
  }
})

export default store
